<script setup>
	import {
		onUnload,
		onShow,
		onLoad
	} from '@dcloudio/uni-app'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({
				audio_url: '',
				duration: 0
			})
		}
	})

	const emit = defineEmits(['startPlay', 'pausePlay', 'endedPlay']);

	import {
		reactive,
		watch,
		ref,
		nextTick,
		onMounted
	} from 'vue'

	const {
		modelValue
	} = props;

	const data = reactive({
		isOpen: false, //播放开关
		startTime: '00:00', //正在播放时长
		duration: '00:00', //总时长
		offset: 0,
		max: 0,
		oldTime: 0,
		isKaoshi: false,
		// src: '',
		current: 1,
		activeName: '0',
		navHeight: 0,
		play: false,
		id: 0,
		info: '',
		beisu: '1.0',
		show: false,
		showBeisu: false,
		mid: 0,
		currentTime: 0, //播放时长
		isFirst: false,
	});

	// onLoad(() => {

	// })

	// watch(
	// 	() => props.modelValue,
	// 	(val) => {
	// 		if(val){
	// 			let num = val.duration.split(':')[0];
	// 			data.max = +num
	// 			data.duration = val.duration
	// 		}
	// 	}, {
	// 		immediate: true
	// 	}
	// )

	const bgMusic = uni.getBackgroundAudioManager();
	bgMusic.onPlay(() => {
		data.isOpen = true;
		emit("startPlay",{})
		
		console.log("播放开始");
	})

	bgMusic.onPause(() => {
		// data.isFirst = true;
		data.isOpen = false;
		emit("pausePlay", {})

		console.log("音乐播放暂停");
	})
	
	bgMusic.onStop(()=>{
		data.isOpen = false;
		data.startTime = "00:00";
		data.offset = 0;
		data.oldTime = data.offset;
		
		emit("endedPlay", {})
		
		console.log("音乐播放停止");
	})

	//播放结束
	bgMusic.onEnded(() => {
		data.startTime = "00:00";
		data.isOpen = false;
		data.offset = 0;
		// data.startTime = "";

		data.oldTime = data.offset;

		emit("endedPlay", {})
		console.log("音乐播放结束");
	})

	bgMusic.onTimeUpdate(() => {
		let duration = bgMusic.duration
		var offset = data.oldTime ? data.oldTime : bgMusic.currentTime

		if (bgMusic.currentTime < 1) return;

		var currentTime = parseInt(bgMusic.currentTime)

		var min = parseInt(currentTime / 60);
		var max = parseInt(bgMusic.duration);
		var endTime = parseInt(bgMusic.duration / 60);
		var sec = currentTime % 60;
		if (sec < 10) {
			sec = "0" + sec;
		};
		if (min < 10) {
			min = "0" + min;
		};
		var sec2 = parseInt(bgMusic.duration) % 60;
		if (sec2 < 10) {
			sec2 = "0" + sec2;
		};
		var startTime = min + ':' + sec; /*  00:00  */
		var endtimeIN = endTime + ':' + sec2; /*  00:00  */

		data.offset = currentTime
		data.startTime = startTime
		data.max = max;
		data.duration = endtimeIN;
		// data.changePlay = true
	})

	let popupRef = ref(null)

	async function startPlay() {
		// play(function(item){
		// 	audioData = item;
		// })

		if (data.isFirst) {
			data.startTime = data.currentTime
			// bgMusic.src = modelValue.audio_url;
		} else {

			bgMusic.epname = modelValue.subtitle;
			// // bgMusic.singer = '歌手名';
			bgMusic.coverImgUrl = modelValue.image;

			if (data.offset != 0) {
				bgMusic.seek(data.offset);
			}

			let title = modelValue.title
			if (modelValue.title) {

			} else {
				title = "7天定制标准化前置内容";
			}
			bgMusic.title = title;
			bgMusic.obeyMuteSwitch = false;
			bgMusic.src = modelValue.audio_url;
			// console.log(222)
		}

		// bgMusic.onPause(()=>{
		// 	data.isFirst = true;
		// 	data.currentTime = bgMusic.currentTime

		// 	data.oldTime = data.offset;

		// 	data.isOpen = false;
		// })

		bgMusic.play();

		emit("startPlay", {});

		data.isOpen = true;
		
		console.log("音乐播放开始")
	}

	function onPause() {

		data.isFirst = true;
		data.currentTime = bgMusic.currentTime

		data.oldTime = data.offset;
		bgMusic.pause();
		// bgMusic.src = "";
		
		// console.log('345', data.oldTime)

		data.isOpen = false;
	}

	function playbackRate(playbackRate) {
		data.isFirst = true;

		data.currentTime = bgMusic.currentTime;
		bgMusic.playbackRate = parseFloat(playbackRate).toFixed(1);

		popupRef.value.close()

		data.beisu = playbackRate

		startPlay();
	}

	function seek(seek) {
		bgMusic.seek(data.offset + seek);
		data.oldTime = data.offset;
		data.isOpen = true;
	}

	onUnload(() => {
		// onPause();
		console.log("离开")
		// destroy()
	})

	// 拖动
	const sliderChanging = ({
		detail
	}) => {
		// if (!this.isDragging) this.isDragging = true
		data.startTime = formatTime(detail.value)
	}

	const sliderChange = ({
		detail
	}) => {
		console.log('🚀 ~ MusicService ~ detail:', detail)
		// this.isDragging = false
		bgMusic.seek(detail.value)
	}

	// 转化为分钟数
	function formatTime(seconds) {
		if (seconds < 0) {
			return '00:00'
		}

		// 计算分钟和剩余秒数
		const minutes = Math.floor(seconds / 60)
		const remainingSeconds = Math.floor(seconds % 60)

		// 格式化为 00:00 形式
		const formattedMinutes = String(minutes).padStart(2, '0')
		const formattedSeconds = String(remainingSeconds).padStart(2, '0')

		return `${formattedMinutes}:${formattedSeconds}`
	}

	// 主动暴露childMethod方法
	defineExpose({
		// onPause
	})
</script>

<template>

	<view class="container" @touchmove.stop="">
		<slider class="progress-box" block-size="12" backgroundColor="#E6E6E6" activeColor="#000" :value="data.offset"
			:max="data.max" @change="sliderChange" @changing="sliderChanging" />

		<view class="time">
			<text class="t-left">{{ data.startTime }}</text>
			<text class="t-right">{{ data.duration }}</text>
		</view>

		<view class="play-box">
			<view class="left" @tap="seek(-15)">
				<image class="pic" src="@/static/icon/player/icon-audio-teek.png" mode="aspectFit" />
				<text class="text">15</text>
			</view>
			<view class="play-icon">
				<image class="pause" v-if="!data.isOpen" @tap="startPlay"
					src="@/static/icon/player/icon-audio-pause.png" mode="aspectFit" />
				<image class="play" @tap="onPause" v-else src="@/static/icon/player/icon-audio-play.png"
					mode="aspectFit" />
			</view>
			<view class="right" @tap="seek(15)">
				<image class="pic" src="@/static/icon/player/icon-audio-teek.png" mode="aspectFit" />
				<text class="text">15</text>
			</view>
		</view>
		<text class="Rate" @tap="popupRef.open()">
			倍速\n
			{{ data.beisu === 1 ? '1.0' : data.beisu }}
		</text>
	</view>
	<uni-popup ref="popupRef" background-color="#fff" type="bottom">
		<view class="popup">
			<view class="p-item" hover-class="hover" @tap="playbackRate(1.0)">1.0</view>
			<view class="p-item" hover-class="hover" @tap="playbackRate(1.25)">1.25</view>
			<view class="p-item" hover-class="hover" @tap="playbackRate(1.5)">1.5</view>
			<view class="p-item" hover-class="hover" @tap="playbackRate(2.0)">2.0</view>
		</view>
	</uni-popup>
</template>

<style lang="scss" scoped>
	.container {
		position: relative;
		margin: 0 auto 50rpx;
		width: 654rpx;
		height: 240rpx;
		border-radius: 8rpx;
		background: rgb(246, 246, 246);
		padding-top: 52rpx;

		.progress-box {
			position: relative;
			margin: 0 auto;
			padding: 0;
			width: 540rpx;
			height: 4rpx;
			border-radius: 2rpx;

			&::before {
				display: none;
			}

			:deep(.wd-slider__button-wrapper) {
				padding: 10rpx;
				top: 50%;
				width: 36rpx;
				height: 36rpx;

				.wd-slider__button {
					width: 100%;
					height: 100%;
					border: 0;
				}
			}
		}

		.time {
			margin-top: 56rpx;
			margin-left: calc(50% - 270rpx);
			padding: 0 16rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			position: absolute;
			top: 20rpx;
			width: 540rpx;
			color: rgb(51, 51, 51);

			.t-left,
			.t-right {
				font-family: PingFang;
				font-size: 26rpx;
				font-weight: 400;
				line-height: 36rpx;
				text-align: center;
			}
		}

		.Rate {
			position: absolute;
			right: 15rpx;
			bottom: 20rpx;
			color: rgb(51, 51, 51);
			font-family: PingFang;
			font-size: 26rpx;
			font-weight: 400;
			line-height: 36rpx;
			text-align: center;
			z-index: 0;
		}

		.play-box {
			margin-top: 43rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: row;

			.play-icon {
				margin: 0 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 112rpx;
				height: 112rpx;
				border-radius: 50%;
				border: 6rpx solid #000;

				.pause {
					margin-left: 8rpx;
					width: 35rpx;
					height: 45rpx;
				}

				.play {
					width: 51rpx;
					height: 51rpx;
				}
			}

			.left,
			.right {
				position: relative;
				width: 40rpx;
				height: 42rpx;
				overflow: visible;

				.pic {
					width: 100%;
					height: 100%;
				}

				.text {
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					color: rgb(51, 51, 51);
					font-family: PingFang;
					font-size: 22rpx;
					font-weight: 500;
					line-height: 40rpx;
				}
			}

			.left {
				transform: rotateY(180deg);

				.text {
					left: 50%;
					transform: translateX(-50%) rotateY(-180deg);
				}
			}
		}
	}

	.popup {
		padding: 30rpx 10rpx;
		background-color: #fff;

		.p-item {
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			font-family: PingFang;
			font-size: 30rpx;
			font-weight: 500;
		}
	}

	.hover {
		background-color: #0001;
	}
</style>